package com.cl.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

import java.io.IOException;
import java.io.InputStream;

public class GPSService extends Service {
	private LocationManager lm;
	private MyListener listener;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		lm = (LocationManager) getSystemService(LOCATION_SERVICE);
		listener = new MyListener();
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		String provider = lm.getBestProvider(criteria, true);
		//获得位置更新
		lm.requestLocationUpdates(provider, 0, 0, listener);
	}
	private class MyListener implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			String longitude = "j:" + location.getLongitude() + "\n";
			String latitude = "w:" + location.getLatitude() + "\n";
			String accuracy = "a" + location.getAccuracy() + "\n";
			
			try {
				InputStream is = getAssets().open("axisoffset.dat");
				ModifyOffset offset = ModifyOffset.getInstance(is);
				offset.s2c(new PointDouble(location.getLongitude(), location.getLatitude()));
				longitude ="j:" + offset.X+ "\n";
				latitude =  "w:" +offset.Y+ "\n";
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			SharedPreferences sp = getSharedPreferences("congfig", MODE_PRIVATE);
			Editor editor = sp.edit();
			editor.putString("lastLocation",  longitude + latitude + accuracy);
			editor.commit();
			
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}
		// 当某一个位置提供者状态发生变化的时候 关闭--》开启 或者开启--》关闭
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		lm.removeUpdates(listener);
		listener = null;
	}
}
